<?php
/**
 *	[TWCMS] (C)2012 TongWang Inc.
 *	$Id: category_model.php 2 2013-04-27 07:14:17Z nanown@qq.com $
 */
class category_model extends admin{
	public $model;

	function __construct() {
		parent::__construct();
		$this->main();
	}

	function main() {
		if(empty($_GET['do'])) {
			$this->model = $this->db->fetch_all('SELECT * FROM `'.TW_DBPRE.'model`');
			include load_tpl(__CLASS__);
		}elseif(!empty($_POST)) {
			if($_GET['do'] == 'ajax_add') {
				$this->ajax_add();
			}elseif($_GET['do'] == 'ajax_edit') {
				$this->ajax_edit();
			}elseif($_GET['do'] == 'ajax_del') {
				$this->ajax_del();
			}
		}elseif($_GET['do'] == 'ajax_get_mid') {
			$this->ajax_get_mid();
		}elseif($_GET['do'] == 'ajax_get_tbody') {
			$this->ajax_get_tbody();
		}
	}

	#增加模型
	function ajax_add() {
		$name = strC($_POST, 'name');
		$tablename = preg_replace('/[^0-9a-zA-z]/', '', strC($_POST, 'tablename'));
		$err = 1;
		$msg = '';
		if(strlen($name) < 2) {
			$msg = '模型名称长度不能小于2';
		}elseif(strlen($tablename) < 2){
			$msg = '数据表名长度不能小于2';
		}elseif($this->db->result_first('SELECT count(*) FROM `'.TW_DBPRE.'model` WHERE tablename='.S($tablename))) {
			$msg = '数据表名不允许重复';
		}elseif(!$this->create_table($tablename)){
			$msg = '创建模型数据表失败';
		}elseif(!$this->db->query("INSERT INTO `".TW_DBPRE."model` (`siteid`, `name`, `tablename`, `index_tpl`, `cate_tpl`, `show_tpl`, `index_url`, `cate_url`, `show_url`) VALUES (0, ".S($name).", '{$tablename}', '{$tablename}_index.htm', '{$tablename}_list.htm', '{$tablename}_show.htm', '{parentdir}/{dir}/index.html', '{parentdir}/{dir}/list_{cid}_{page}.html', '{y}/{m}{d}/{id}.html')")){
			$msg = '增加模型失败';
		}else{
			$err = 0;
			$msg = '增加模型完成';
		}
		exit('{"err" : '.$err.', "msg" : "'.$msg.'"}');
	}

	#编辑模型
	function ajax_edit() {
		$mid = intget('mid');
		$name = strC($_POST, 'name');
		$tablename = str_preg(strC($_POST, 'tablename'));
		$err = 1;
		$msg = '';
		if($mid < 3) {
			$msg = '不允许修改模型ID小于3的模型';
		}elseif(strlen($name) < 2) {
			$msg = '模型名称长度不能小于2';
		}elseif(strlen($tablename) < 2){
			$msg = '数据表名长度不能小于2';
		}elseif(!$oldtablename = $this->db->result_first('SELECT tablename FROM `'.TW_DBPRE.'model` WHERE mid='.$mid.' LIMIT 1')) {
			$msg = '此模型不存在';
		}elseif(!$this->rename_table($oldtablename, $tablename)) {
			$msg = '修改模型数据表失败';
		}elseif(!$this->db->query('UPDATE `'.TW_DBPRE.'model` SET `name`="'.addslashes($name).'",`tablename`="'.addslashes($tablename).'"'.($oldtablename != $tablename ? ',`index_tpl`="'.$tablename.'_index.htm", `cate_tpl`="'.$tablename.'_list.htm", `show_tpl`="'.$tablename.'_show.htm"' : '').' WHERE `mid`='.$mid)) {
			$msg = '修改模型失败';
		}else{
			$err = 0;
			$msg = '修改模型完成';
		}
		exit('{"err" : '.$err.', "msg" : "'.$msg.'"}');
	}

	#删除模型
	function ajax_del() {
		$mid = intC($_POST, 'mid');
		$err = 1;
		$msg = '';
		if(empty($mid)) {
			$msg = '模型ID不能为空';
		}elseif(!$modArr = $this->db->fetch_first('SELECT issystem,tablename FROM `'.TW_DBPRE.'model` WHERE mid='.$mid.' LIMIT 1')) {
			$msg = '此模型不存在';
		}elseif($modArr['issystem']) {
			$msg = '不允许删除系统模型';		
		}elseif($this->db->result_first('SELECT count(*) FROM `'.TW_DBPRE.'category` WHERE mid='.$mid)) {
			$msg = '此模型已经创建了分类，请先删除此模型的所有分类';			
		}elseif(!$this->db->query('DROP TABLE `'.TW_DBPRE.'cms_'.$modArr['tablename'].'`, `'.TW_DBPRE.'cms_'.$modArr['tablename'].'_comment`, `'.TW_DBPRE.'cms_'.$modArr['tablename'].'_data`, `'.TW_DBPRE.'cms_'.$modArr['tablename'].'_tags`, `'.TW_DBPRE.'cms_'.$modArr['tablename'].'_tagsdata`;')){
			$msg = '删除模型数据表失败';
		}elseif(!$this->db->query('DELETE FROM `'.TW_DBPRE.'model` WHERE `mid`='.$mid)) {
			$msg = '删除模型失败';
		}else{
			$err = 0;
			$msg = '删除模型完成';
		}
		exit('{"err" : '.$err.', "msg" : "'.$msg.'"}');
	}

	#创建模型数据表
	function create_table($tablename) {
		require base::load_sys_file('model_sql', 'twcms');
		$ret = true;
		foreach($model_sql as $row) {
			$colsql=array();
			foreach($row['field'] as $key=>$val) {
				$colsql[] = '`'.$key.'` '.$val.',';
			}
			$this->db->query('CREATE TABLE IF NOT EXISTS `'.$row['table'].'` ('.implode('',$colsql).$row['extra'].') ENGINE=MyISAM DEFAULT CHARSET=utf8;') || $ret = false;
		}
		return $ret;
	}

	#修改模型数据表名
	function rename_table($oldtablename, $tablename) {
		$ret = true;
		if($oldtablename != $tablename) {
			$this->db->query('RENAME TABLE `'.TW_DBPRE.'cms_'.$oldtablename.'` TO `'.TW_DBPRE.'cms_'.$tablename.'`') || $ret = false;
			$this->db->query('RENAME TABLE `'.TW_DBPRE.'cms_'.$oldtablename.'_data` TO `'.TW_DBPRE.'cms_'.$tablename.'_data`') || $ret = false;
			$this->db->query('RENAME TABLE `'.TW_DBPRE.'cms_'.$oldtablename.'_comment` TO `'.TW_DBPRE.'cms_'.$tablename.'_comment`') || $ret = false;
			$this->db->query('RENAME TABLE `'.TW_DBPRE.'cms_'.$oldtablename.'_tags` TO `'.TW_DBPRE.'cms_'.$tablename.'_tags`') || $ret = false;
			$this->db->query('RENAME TABLE `'.TW_DBPRE.'cms_'.$oldtablename.'_tagsdata` TO `'.TW_DBPRE.'cms_'.$tablename.'_tagsdata`') || $ret = false;
		}
		return $ret;
	}

	#获取编辑数据
	function ajax_get_mid() {
		exit(tojson($this->db->fetch_first('SELECT name,tablename FROM `'.TW_DBPRE.'model` WHERE mid='.intget('mid').' LIMIT 1')));
	}

	#获取最新模型数据
	function ajax_get_tbody() {
		$modelArr = $this->db->fetch_all('SELECT * FROM `'.TW_DBPRE.'model`');
		foreach($modelArr as $lv) {
			echo '<tr class="li">';
			echo '<td>'.$lv['mid'].'</td>';
			echo '<td>'.($lv['mid']<2 ? '' : '<a class="field">[字段管理]</a> <a class="edit">[编辑]</a> ').($lv['issystem'] ? '' : '<a class="del">[删除]</a>').'</td>';
			echo '<td>'.$lv['name'].'</td>';
			echo '<td>'.$lv['tablename'].'</td>';
			echo '<td>'.($lv['issystem'] ? '<font color="red">系统</font>' : '自定义').'</td>';
			echo '</tr>';
		}
		exit();
	}
}